<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="代理级别" prop="agentLevel">
            <el-select
              v-model="queryParams.agentLevel"
              placeholder="代理级别"
              clearable
              size="small"
            >
              <el-option
                v-for="item in agentLevelOptions"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="门店名称" prop="title">
            <el-input v-model="queryParams.name" placeholder="请输入门店名称" clearable size="small"/>
          </el-form-item>
          <el-form-item label="负责人" prop="title">
            <el-input v-model="queryParams.principal" placeholder="请输入门店负责人" clearable size="small"/>
          </el-form-item>
          <el-form-item label="位置" prop="title">
            <el-input v-model="queryParams.location" placeholder="请输入门店位置" clearable size="small"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['agent:store:query']"
            >搜索
            </el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['agent:store:add']"
            >新增
            </el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['agent:store:export']"
                       @click="handleExport"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="storeList" border>
          <el-table-column label="门店名称" align="center" prop="name" :show-overflow-tooltip="true"/>
          <el-table-column
            label="门店图片"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-popover
                placement="right"
                trigger="hover"
              >
                <img :src="scope.row.storeImg" width="400" alt=""/>
                <img slot="reference" :src="scope.row.storeImg" style="width: 25px;height: 25px">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="负责人" align="center" prop="principal" width="120" :show-overflow-tooltip="true"/>
          <el-table-column label="联系电话" align="center" prop="phone" width="120"/>
          <el-table-column label="位置" align="center" prop="location" :show-overflow-tooltip="true"/>
          <el-table-column label="经度" align="center" prop="longitude" v-if="false"/>
          <el-table-column label="纬度" align="center" prop="latitude" v-if="false"/>
          <el-table-column label="门店图片" align="center" prop="storeImg" v-if="false"/>
          <el-table-column label="地图标签图片" align="center" prop="markerImg" v-if="false"/>
          <el-table-column label="代理级别" align="center" prop="agentLevel" width="150">
            <template slot-scope="scope">
              <el-tag
                :type="tagTypes[getSafeIndex(getIndexOfArray(agentLevelLabels,scope.row.agentLevel),tagTypes.length)]"
              >
                {{ scope.row.agentLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开业时间" align="center" prop="startBusinessTime" width="120"/>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['agent:store:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['agent:store:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-form-item label="所属组织" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
                        placeholder="请选择归属组织"
            />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="代理级别" prop="agentLevel">
                <el-select v-model="form.agentLevel"
                           placeholder="代理级别"
                           size="small"
                >
                  <el-option v-for="item in agentLevelOptions"
                             :key="item.dictCode"
                             :label="item.dictLabel"
                             :value="item.dictCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="门店名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入门店名称"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-col :span="12">
            <el-form-item label="联系人" prop="principal">
              <el-input v-model="form.principal" placeholder="请输入门店联系人"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开业时间" prop="startBusinessTime">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="所在区域" prop="district">
              <el-cascader ref="districtCascader" :props="districtSelectProps" v-model="districtText"
                           :separator="''"
                           :key="modelKey"
                           @change="handleChangeDistrict"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在位置" prop="district">
              <el-col :span="18">
                <el-input id="formAddress" @focus="onAddressInputFocus" v-model="form.address" placeholder="选择地址"
                          :readonly="true"
                />
              </el-col>
              <el-col :span="6">
                <i class="el-icon-location-information" style="font-size: 25px" @click="setShowLocationMap(true)"/>
              </el-col>
              <addressSearch v-on:returnAddress="receiveAddressInfoFromSearch"
                             v-on:setVisible="(value)=>this.showLocationMap=value"
                             :visible="showLocationMap"
                             :city-code="selectCityCode"
                             :center="selectCenter"
                             :address="tempAddress"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="form.detailAddress" placeholder="详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <center>
              <div style="width: 50px;height: 50px;">
                <img :src="storeImgUrl" v-if="storeImgUrl" style="width: 50px;height: 50px">
              </div>
            </center>
          </el-col>

          <el-col :span="6">
            <center>
              <div style="width: 50px;height: 50px;">
                <img :src="markerImgUrl" v-if="markerImgUrl" style="width: 50px;height: 50px">
              </div>
            </center>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <!-- 门店图片上传-->
            <center>
              <el-form-item prop="storeImage" label-width="0">
                <el-upload
                  ref="storeImageUpload"
                  accept=".jpg, .png"
                  :headers="headers"
                  :action="imgUploadUrl"
                  :data="{path: 'zyzn/agent/'}"
                  :on-change="storeImgUpLoadChange"
                  :disabled="storeImgUploading"
                  :on-progress="handleStoreImgUploadProgress"
                  :on-success="handleStoreImgSuccess"
                  :auto-upload="true"
                  :show-file-list="false"
                  list-type="picture"
                >
                  <el-button size="small" style="margin-top: 5px;margin-bottom: 5px">上传门店图片</el-button>
                </el-upload>
              </el-form-item>
            </center>
          </el-col>

          <el-col :span="6">
            <!-- 门店标记图片上传-->
            <center>
              <el-form-item label-width="0" prop="markerImage">
                <el-upload
                  ref="markerImageUpload"
                  accept=".jpg, .png"
                  :headers="headers"
                  :action="imgUploadUrl"
                  :data="{path: 'zyzn/agent/'}"
                  :on-change="markerImgUpLoadChange"
                  :disabled="markerImgUploading"
                  :on-progress="handleMarkerImgUploadProgress"
                  :on-success="handleMarkerImgSuccess"
                  :auto-upload="true"
                  :show-file-list="false"
                  list-type="picture"
                >
                  <el-button size="small" style="margin-top: 5px;margin-bottom: 5px">上传标记图片</el-button>
                </el-upload>
              </el-form-item>
            </center>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addStore, delStore, exportStore, listStore, updateStore } from '@/api/system/agent'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
import { deptTreeSelect } from '@/api/system/dept'
import { dateStrToDate, myDateFormat } from '@/utils/TimeUtils'
import { getToken } from '@/utils/auth'
import addressSearch from '@/views/components/addressSearch/index'
import { fetchFieldFromObjectArray, getIndexOfArray, getSafeIndex } from '@/api/system/arrayUtils'
import axios from 'axios'
import { deepClone, hasText, hasValue } from '@/api/system/commonUtils'

export default {
  name: 'index',
  components: { Treeselect, addressSearch },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 代理门店信息表格数据
      storeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        name: undefined,
        principal: undefined,
        phone: undefined,
        location: undefined,
        agentLevel: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: [],
      // 当前选择的组织
      selectedOrgCode: null,
      agentLevelOptions: [],
      // 选择的日期
      selectedDate: null,
      storeImgUrl: undefined,
      storeImgUploading: undefined,
      storeImgObject: undefined,
      markerImgUrl: undefined,
      markerImgUploading: undefined,
      markerImgObject: undefined,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      // 上传的地址
      imgUploadUrl: process.env.VUE_APP_BASE_API + '/system/image/uploadImage',
      locationMap: undefined,
      searchPositionText: undefined,
      districtSearch: undefined,
      districtSelectProps: {
        lazy: true,
        lazyLoad: this.lazyLoad
      },
      districtText: undefined,
      dialogTestShow: false,
      agentLevelLabels: [],
      tagTypes: ['danger', 'warning', 'success', 'info'],
      // 区域级联选择的key, 每次编辑时修改, 重新渲染, 以使组件回显数据
      modelKey: 0,
      showLocationMap: false,
      selectCityCode: '全国',
      selectCenter: [],
      tempCenter: [],
      hasSelectDistrict: false,
      hasSelectAddress: false,
      tempAddress: ''
    }
  },
  watch: {
    // districtText(value) {
    //   console.log(value)
    // }
  },
  created() {
    // 等待查询组织树和字典返回
    axios.all([deptTreeSelect(), this.getDictDataByType('agent_level')])
      .then(axios.spread((response1, response2) => {
        // 查询组织树返回
        this.deptOptions = response1.data

        // 查询代理级别字典返回
        this.agentLevelOptions = response2.data
        if (response2.data && response2.data.length > 0) {
          this.agentLevelLabels = fetchFieldFromObjectArray(response2.data, 'dictLabel')
        }

        // 查询门店列表
        this.getList()
      }))

    AMap.plugin('AMap.DistrictSearch', () => {
      this.districtSearch = new AMap.DistrictSearch({
        level: 'country'
        // subdistrict: 1
      })
    })
  },
  mounted() {

  },
  methods: {
    getIndexOfArray,
    getSafeIndex,
    /** 查询代理门店信息列表 */
    getList() {
      this.loading = true
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.storeImgUrl = null
      this.storeImgObject = null
      this.tempCenter = []
      this.tempCenter = ''
      this.markerImgUrl = null
      this.markerImgObject = null
      this.selectedDate = null
      this.districtText = null
      this.hasSelectDistrict = false
      this.hasSelectAddress = false
      this.reset()
      this.form.deptId = this.selectedOrgCode
      this.open = true
      this.title = '添加门店信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.selectedDate = null
      this.hasSelectDistrict = true
      this.hasSelectAddress = true
      this.form = JSON.parse(JSON.stringify(row))

      // 字符串转换为date
      if (this.form.startBusinessTime) {
        this.selectedDate = dateStrToDate(this.form.startBusinessTime, myDateFormat)
      }
      // 将label替换为value
      if (this.form.agentLevel) {
        let temp = this.form.agentLevel
        for (let i = 0, len = this.agentLevelOptions.length; i < len; i++) {
          if (this.agentLevelOptions[i].dictLabel === temp) {
            this.form.agentLevel = this.agentLevelOptions[i].dictCode
          }
        }
      }

      this.districtText = row.district.split(' ')
      // let districtNameList = row.district.split(' ')
      // let districtObjectList = []
      // for (let i = 0, len = districtNameList.length; i < len; i++) {
      //   districtObjectList.push({ name: districtNameList[i], center: [], cityCode: '', adCode: '' })
      // }
      //
      // this.districtText = districtObjectList
      // console.log(this.districtText)

      if (this.modelKey > 1000) {
        this.modelKey = 0
      } else {
        this.modelKey++
      }
      this.tempCenter = [row.longitude, row.latitude]
      this.tempAddress = row.address

      this.storeImgUrl = this.form.storeImg
      this.storeImgObject = null
      this.markerImgUrl = this.form.markerImg
      this.markerImgObject = null

      this.open = true
      this.title = '修改门店信息'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 将开业时间的date类型转为毫秒时间戳
          if (this.selectedDate) {
            this.form.startBusinessTime = this.selectedDate.getTime()
          } else {
            this.form.startBusinessTime = null
          }
          // 处理图片地址
          this.storeImgObject ? this.form.storeImg = this.storeImgObject.url : this.form.storeImg = null
          this.markerImgObject ? this.form.markerImg = this.markerImgObject.url : this.form.markerImg = null

          if (this.districtText && this.districtText.length > 0) {
            // this.form.district = fetchFieldFromObjectArray(this.districtText, 'name').join(' ')
            this.form.district = this.districtText.join(' ')
          }

          // 若是修改
          if (this.form.id !== undefined) {
            updateStore(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            // 若是新增
            addStore(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: null,
        name: undefined,
        principal: undefined,
        phone: undefined,
        district: undefined,
        address: undefined,
        location: undefined,
        startBusinessTime: null,
        storeImg: undefined,
        markerImg: undefined
      }
      this.resetForm('form')
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delStore(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportStore(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.selectedOrgCode = data.id
      this.handleQuery()
    },
    // 上传图片钩子
    storeImgUpLoadChange(file, fileList) {
      this.storeImgUrl = file.url
      // 只保留最新的文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleStoreImgUploadProgress() {
      this.storeImgUploading = true
    },
    handleStoreImgSuccess(response, file, fileList) {
      this.storeImgObject = response.data
      this.$refs.storeImageUpload.clearFiles()
      this.storeImgUploading = false
    },
    markerImgUpLoadChange(file, fileList) {
      this.markerImgUrl = file.url
      // 只保留最新的文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleMarkerImgUploadProgress() {
      this.markerImgUploading = true
    },
    handleMarkerImgSuccess(response, file, fileList) {
      this.markerImgObject = response.data
      this.$refs.markerImageUpload.clearFiles()
      this.markerImgUploading = false
    },
    lazyLoad(node, resolve) {
      let districtLevel = null
      switch (node.level) {
        case 0:
          districtLevel = 'country'
          break
        case 1:
          districtLevel = 'province'
          break
        case 2:
          districtLevel = 'city'
          break
        default:
          break
      }

      if (districtLevel) {
        this.districtSearch.setLevel(districtLevel)
        let searchText = node.value ? node.value : '中国'
        this.districtSearch.search(searchText, (status, result) => {
          if (status === 'complete') {
            if (districtLevel === 'city') {
              this.selectCityCode = result.districtList[0].citycode
              this.selectCenter = [result.districtList[0].center.R, result.districtList[0].center.Q]
            }

            // console.log(JSON.stringify(result))
            // console.log(result)

            let nodes = []
            let districtList = result.districtList[0].districtList
            for (let i = 0, len = districtList.length; i < len; i++) {
              nodes.push({
                label: districtList[i].name,
                adCode: districtList[i].adcode,
                cityCode: districtList[i].citycode,
                center: [districtList[i].center.R, districtList[i].center.Q],
                value: districtList[i].name,
                leaf: node.level >= 2
              })
            }

            resolve(nodes)
          }
        })
      }
    },

    onAddressInputFocus() {
      if (!hasText(this.form.address)) {
        this.setShowLocationMap(true)
      }
    },
    receiveAddressInfoFromSearch(data) {
      if (data.status === 200) {
        this.form.address = data.address
        this.form.longitude = data.position.R
        this.form.latitude = data.position.Q
      }
    },
    handleChangeDistrict(value) {
      let node = this.$refs.districtCascader.getCheckedNodes()[0]
      let nodeData = node.data
      this.selectCityCode = nodeData.cityCode
      this.selectCenter = nodeData.center
      this.hasSelectDistrict = true
    },
    setShowLocationMap(value) {
      if (value && !this.hasSelectDistrict) {
        this.msgInfo('请先选择区域')
        return
      }
      if (this.tempCenter.length > 0) {
        this.selectCenter = deepClone(this.tempCenter)
      }
      this.showLocationMap = value
    }
  }
}
</script>

<style scoped>

</style>
